/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.power.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.mgt.domain.dto.power.RoleResourceDTO;
import com.iwindplus.mgt.server.mapper.power.ResourceMapper;
import com.iwindplus.mgt.server.mapper.power.RoleResourceMapper;
import com.iwindplus.mgt.server.model.power.ResourceDO;
import com.iwindplus.mgt.server.model.power.RoleResourceDO;
import com.iwindplus.mgt.server.service.power.RoleResourceService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 角色资源关系业务层接口实现类.
 *
 * @author zengdegui
 * @since 2018/9/1
 */
@Service
@CacheConfig(cacheNames = {"roleResource"})
@Transactional(rollbackFor = Exception.class)
public class RoleResourceServiceImpl extends JoinCrudRepository<RoleResourceMapper, RoleResourceDO>
    implements RoleResourceService {

    @Resource
    private ResourceMapper resourceMapper;

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean save(RoleResourceDTO entity) {
        List<RoleResourceDO> entities = new ArrayList<>(10);
        final RoleResourceDO model = BeanUtil.copyProperties(entity, RoleResourceDO.class);
        this.buildParam(model, entities);
        if (CollUtil.isNotEmpty(entities)) {
            super.saveBatch(entities, DEFAULT_BATCH_SIZE);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean saveBatchResource(Long roleId, Set<Long> resourceIds) {
        if (CollUtil.isEmpty(resourceIds)) {
            return Boolean.FALSE;
        }
        final List<ResourceDO> list = this.resourceMapper.selectList(Wrappers.<ResourceDO>lambdaQuery()
            .in(ResourceDO::getId, resourceIds)
            .eq(ResourceDO::getStatus, EnableStatusEnum.ENABLE)
            .select(ResourceDO::getId, ResourceDO::getMenuId));
        if (CollUtil.isEmpty(list)) {
            return Boolean.FALSE;
        }
        Map<Long, Long> dataMap = list.stream()
            .collect(Collectors.toMap(ResourceDO::getId, ResourceDO::getMenuId));
        if (MapUtil.isEmpty(dataMap)) {
            return Boolean.FALSE;
        }
        List<RoleResourceDO> entities = new ArrayList<>(10);
        resourceIds.stream().forEach(resourceId -> {
            RoleResourceDO entity = RoleResourceDO.builder()
                .roleId(roleId)
                .menuId(dataMap.get(resourceId))
                .resourceId(resourceId)
                .build();
            this.buildParam(entity, entities);
        });
        if (CollUtil.isNotEmpty(entities)) {
            super.saveBatch(entities, DEFAULT_BATCH_SIZE);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean saveBatchRole(Long resourceId, Set<Long> roleIds) {
        if (CollUtil.isEmpty(roleIds)) {
            return Boolean.FALSE;
        }
        final ResourceDO data = this.resourceMapper.selectOne(Wrappers.<ResourceDO>lambdaQuery()
            .eq(ResourceDO::getId, resourceId).select(ResourceDO::getMenuId));
        if (Objects.isNull(data)) {
            return Boolean.FALSE;
        }
        List<RoleResourceDO> entities = new ArrayList<>(10);
        roleIds.stream().forEach(roleId -> {
            RoleResourceDO entity = RoleResourceDO.builder()
                .roleId(roleId)
                .menuId(data.getMenuId())
                .resourceId(resourceId)
                .build();
            this.buildParam(entity, entities);
        });
        if (CollUtil.isNotEmpty(entities)) {
            super.saveBatch(entities, DEFAULT_BATCH_SIZE);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean saveBatch(List<RoleResourceDTO> entities) {
        if (CollUtil.isEmpty(entities)) {
            return Boolean.FALSE;
        }
        List<RoleResourceDO> params = new ArrayList<>(10);
        entities.stream().forEach(entity -> {
            RoleResourceDO model = BeanUtil.copyProperties(entity, RoleResourceDO.class);
            this.buildParam(model, params);
        });
        if (CollUtil.isNotEmpty(params)) {
            super.saveBatch(params, DEFAULT_BATCH_SIZE);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean removeByIds(List<Long> ids) {
        return CollUtil.isNotEmpty(ids) && SqlHelper.retBool(super.baseMapper.deleteByIds(ids));
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean removeByRoleIds(List<Long> roleIds) {
        return CollUtil.isNotEmpty(roleIds) && SqlHelper.retBool(super.baseMapper.deleteByRoleIds(roleIds));
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean removeByMenuIds(List<Long> menuIds) {
        return CollUtil.isNotEmpty(menuIds) && SqlHelper.retBool(super.baseMapper.deleteByMenuIds(menuIds));
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean removeByResourceIds(List<Long> resourceIds) {
        return CollUtil.isNotEmpty(resourceIds) && SqlHelper.retBool(super.baseMapper.deleteByResourceIds(resourceIds));
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean editBatchResource(Long roleId, Set<Long> resourceIds) {
        this.removeByRoleIds(Arrays.asList(roleId));
        this.saveBatchResource(roleId, resourceIds);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean editBatchRole(Long resourceId, Set<Long> roleIds) {
        this.removeByResourceIds(Arrays.asList(resourceId));
        this.saveBatchRole(resourceId, roleIds);
        return Boolean.TRUE;
    }


    private void buildParam(RoleResourceDO entity, List<RoleResourceDO> entities) {
        long count = super.count(Wrappers.lambdaQuery(RoleResourceDO.class)
            .eq(RoleResourceDO::getRoleId, entity.getRoleId())
            .eq(RoleResourceDO::getMenuId, entity.getMenuId())
            .eq(RoleResourceDO::getResourceId, entity.getResourceId()));
        if (!SqlHelper.retBool(count)) {
            entities.add(entity);
        }
    }
}
